import axios from "axios";
export default {
  namespaced: true,
  state: () => ({
    cart: []
  }),
  mutations: {
    updateCartList(state, pay) {
      state.cart = pay;
    },
    updateGoodsState(state, pay) {
      let index = state.cart.findIndex(item => item.id === pay.id);
      state.cart[index].goods_state = pay.value;
    },
    shu(state, pay) {
      let index = state.cart.findIndex(item => item.id === pay.id);
      state.cart[index].goods_count = pay.value;
    },
    sh(state, pay) {
      state.cart.forEach(item => (item.goods_state = pay.val));
    }
  },
  actions: {
    async getCartList(context) {
      const res = await axios({
        url: "https://www.escook.cn/api/cart"
      });
      console.log(res);
      context.commit("updateCartList", res.data.list);
    }
  },
  getters: {
    isall(state) {
      return state.cart
        .filter(item => item.goods_state)
        .reduce((sum, item) => (sum += item.goods_count * item.goods_price), 0);
    },
    opp(state) {
      return state.cart
        .filter(item => item.goods_state)
        .reduce((sum, item) => (sum += item.goods_count), 0);
    }
  }
};
